<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    :title="dialogTitle"
    width="700px"
    :close-on-click-modal="false"
    @close="handleClose"
    :fullscreen="isMobile"
  >
    <div class="dialog-content">
      <!-- 日期信息 -->
      <div class="date-info">
        <div class="date-title">{{ formatDate(selectedDate) }}</div>
        <div class="date-stats">
          <div class="stat-item">
            <div class="stat-label">总日程</div>
            <div class="stat-value">{{ totalSchedules }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">待处理</div>
            <div class="stat-value pending">{{ pendingCount }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">已完成</div>
            <div class="stat-value completed">{{ completedCount }}</div>
          </div>
        </div>
      </div>

      <!-- 日程列表 -->
      <div class="schedules-container">
        <div v-if="sortedSchedules.length === 0" class="empty-state">
          <el-empty description="该日期暂无日程" />
        </div>
        
        <div v-else class="schedule-list">
          <div
            v-for="schedule in sortedSchedules"
            :key="schedule.id"
            class="schedule-item"
            :class="getScheduleClass(schedule)"
            @click="handleScheduleClick(schedule)"
          >
            <div class="schedule-header">
              <div class="schedule-time">
                <el-icon><Clock /></el-icon>
                {{ formatTimeRange(schedule.start_time, schedule.end_time) }}
              </div>
              <div class="schedule-status">
                <el-icon :class="getStatusIconClass(schedule.status || 'pending')">
                  {{ getStatusIcon(schedule.status || 'pending') }}
                </el-icon>
                {{ getStatusText(schedule.status || 'pending') }}
              </div>
            </div>
            
            <div class="schedule-body">
              <div class="schedule-title">{{ schedule.title }}</div>
              <div v-if="schedule.description" class="schedule-description">
                {{ schedule.description }}
              </div>
            </div>
            
            <div class="schedule-footer">
              <div class="schedule-priority">
                <div class="priority-indicator" :class="getPriorityIndicatorClass(schedule.priority || 'low')"></div>
                <span>{{ getPriorityText(schedule.priority || 'low') }}</span>
              </div>
              <div class="schedule-actions">
                <el-button
                  size="small"
                  text
                  @click.stop="handleScheduleClick(schedule)"
                >
                  查看详情
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { useScheduleStore } from '@/stores/schedule'
import type { ScheduleResponse } from '@/api/models'
import { Clock, Loading, CircleCheck, CircleClose } from '@element-plus/icons-vue'

interface Props {
  visible: boolean
  selectedDate: string
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'schedule-click', schedule: ScheduleResponse): void
  (e: 'create-schedule', date: string): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  selectedDate: ''
})

const emit = defineEmits<Emits>()

const scheduleStore = useScheduleStore()

// 响应式状态
const isMobile = ref(window.innerWidth <= 768)

// 监听窗口大小变化
const handleResize = () => {
  isMobile.value = window.innerWidth <= 768
}

// 组件挂载时添加监听
onMounted(() => {
  window.addEventListener('resize', handleResize)
})

// 组件卸载时移除监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

// 计算属性
const dialogTitle = computed(() => {
  return `${formatDate(props.selectedDate)} 的日程`
})

// 获取指定日期的日程
const schedulesForDate = computed(() => {
  return scheduleStore.schedules.filter(schedule => {
    const scheduleDate = new Date(schedule.start_time).toISOString().split('T')[0]
    return scheduleDate === props.selectedDate
  })
})

// 获取排序后的日程（已完成日程放到最后）
const sortedSchedules = computed(() => {
  return schedulesForDate.value.sort((a, b) => {
    // 已完成的日程放到最后
    if (a.status === 'completed' && b.status !== 'completed') return 1
    if (a.status !== 'completed' && b.status === 'completed') return -1
    
    // 已取消的日程也放到最后
    if (a.status === 'cancelled' && b.status !== 'cancelled') return 1
    if (a.status !== 'cancelled' && b.status === 'cancelled') return -1
    
    // 其他状态按开始时间排序
    return new Date(a.start_time).getTime() - new Date(b.start_time).getTime()
  })
})

// 统计数据
const totalSchedules = computed(() => schedulesForDate.value.length)
const pendingCount = computed(() => 
  schedulesForDate.value.filter(s => s.status === 'pending').length
)
const completedCount = computed(() => 
  schedulesForDate.value.filter(s => s.status === 'completed').length
)

// 方法
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  })
}

const formatTimeRange = (startTime: string, endTime: string) => {
  const start = new Date(startTime)
  const end = new Date(endTime)
  return `${start.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })} - ${end.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}`
}

const getScheduleClass = (schedule: ScheduleResponse) => {
  return {
    [`priority-${schedule.priority}`]: true,
    [`status-${schedule.status}`]: true
  }
}

const getPriorityIndicatorClass = (priority: string) => {
  return `priority-indicator-${priority}`
}

const getStatusIcon = (status: string) => {
  switch (status) {
    case 'pending':
      return Clock
    case 'in_progress':
      return Loading
    case 'completed':
      return CircleCheck
    case 'cancelled':
      return CircleClose
    default:
      return Clock
  }
}

const getStatusIconClass = (status: string) => {
  return `status-icon-${status}`
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'pending':
      return '待处理'
    case 'in_progress':
      return '进行中'
    case 'completed':
      return '已完成'
    case 'cancelled':
      return '已取消'
    default:
      return '未知'
  }
}

const getPriorityText = (priority: string) => {
  switch (priority) {
    case 'urgent':
      return '紧急'
    case 'high':
      return '高'
    case 'medium':
      return '中'
    case 'low':
      return '低'
    default:
      return '未知'
  }
}

const handleScheduleClick = (schedule: ScheduleResponse) => {
  emit('schedule-click', schedule)
}

const handleClose = () => {
  emit('update:visible', false)
}
</script>

<style scoped>
.dialog-content {
  max-height: 60vh;
  overflow-y: auto;
}

/* 日期信息 */
.date-info {
  background: linear-gradient(135deg, var(--el-color-primary-light-9) 0%, var(--el-bg-color) 100%);
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  border: 1px solid var(--el-border-color-light);
}

.date-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin-bottom: 12px;
  text-align: center;
}

.date-stats {
  display: flex;
  justify-content: space-around;
  gap: 16px;
}

.stat-item {
  text-align: center;
  flex: 1;
}

.stat-label {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-bottom: 4px;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.stat-value.pending {
  color: #E6A23C;
}

.stat-value.completed {
  color: #67C23A;
}

/* 日程容器 */
.schedules-container {
  min-height: 200px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.schedule-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.schedule-item {
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-light);
  border-radius: 12px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.schedule-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  border-color: var(--el-color-primary);
}

.schedule-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.schedule-time {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-regular);
}

.schedule-status {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  font-weight: 500;
  padding: 4px 8px;
  border-radius: 12px;
  background: rgba(var(--el-color-primary-rgb), 0.1);
}

.schedule-body {
  margin-bottom: 12px;
}

.schedule-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
  line-height: 1.4;
}

.schedule-description {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  line-height: 1.5;
}

.schedule-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.schedule-priority {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.priority-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  flex-shrink: 0;
}

.schedule-actions {
  display: flex;
  gap: 8px;
}

/* 优先级样式 */
.schedule-item.priority-urgent {
  border-left: 4px solid #DC143C;
}

.schedule-item.priority-high {
  border-left: 4px solid #F56C6C;
}

.schedule-item.priority-medium {
  border-left: 4px solid #E6A23C;
}

.schedule-item.priority-low {
  border-left: 4px solid #909399;
}

/* 状态样式 */
.schedule-item.status-completed {
  opacity: 0.7;
  background: linear-gradient(135deg, rgba(103, 194, 58, 0.05) 0%, rgba(133, 206, 97, 0.02) 100%);
}

.schedule-item.status-cancelled {
  opacity: 0.5;
  background: linear-gradient(135deg, rgba(245, 108, 108, 0.05) 0%, rgba(247, 137, 137, 0.02) 100%);
}

/* 优先级指示器 */
.priority-indicator-urgent {
  background: linear-gradient(135deg, #FF1744 0%, #FF5252 100%);
}

.priority-indicator-high {
  background: linear-gradient(135deg, #FF6B6B 0%, #FF8E8E 100%);
}

.priority-indicator-medium {
  background: linear-gradient(135deg, #FFB84D 0%, #FFCC7A 100%);
}

.priority-indicator-low {
  background: linear-gradient(135deg, #B1B3B8 0%, #D3D5D8 100%);
}

/* 状态图标样式 */
.status-icon {
  font-size: 14px;
}

.status-icon-pending {
  color: #E6A23C;
}

.status-icon-in-progress {
  color: #409EFF;
  animation: spin 2s linear infinite;
}

.status-icon-completed {
  color: #67C23A;
}

.status-icon-cancelled {
  color: #F56C6C;
}

/* 对话框底部 */
.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dialog-content {
    max-height: 50vh;
  }
  
  .date-info {
    padding: 16px;
    margin-bottom: 16px;
  }
  
  .date-title {
    font-size: 16px;
    margin-bottom: 8px;
  }
  
  .date-stats {
    gap: 12px;
  }
  
  .stat-value {
    font-size: 16px;
  }
  
  .schedule-item {
    padding: 12px;
  }
  
  .schedule-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
    margin-bottom: 8px;
  }
  
  .schedule-time {
    font-size: 12px;
  }
  
  .schedule-status {
    font-size: 11px;
  }
  
  .schedule-title {
    font-size: 14px;
    margin-bottom: 6px;
  }
  
  .schedule-description {
    font-size: 12px;
  }
  
  .schedule-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .dialog-footer {
    flex-direction: column-reverse;
    gap: 12px;
  }
  
  .dialog-footer .el-button {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .date-info {
    padding: 12px;
    margin-bottom: 12px;
  }
  
  .date-title {
    font-size: 14px;
  }
  
  .date-stats {
    gap: 8px;
  }
  
  .stat-value {
    font-size: 14px;
  }
  
  .schedule-item {
    padding: 10px;
  }
  
  .schedule-title {
    font-size: 13px;
  }
  
  .schedule-description {
    font-size: 11px;
  }
}

/* 动画效果 */
@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 深色模式优化 */
@media (prefers-color-scheme: dark) {
  .date-info {
    background: linear-gradient(135deg, rgba(var(--el-color-primary-rgb), 0.1) 0%, var(--el-bg-color-overlay) 100%);
    border-color: var(--el-border-color-darker);
  }
  
  .schedule-item {
    background: var(--el-bg-color-overlay);
    border-color: var(--el-border-color-darker);
  }
  
  .schedule-item:hover {
    border-color: var(--el-color-primary);
  }
  
  .schedule-status {
    background: rgba(var(--el-color-primary-rgb), 0.15);
  }
}
</style>
